use std::collections::HashMap;
use serde_json::Value;
use tracing::debug;
use tracing::field::debug;
use crate::http::get_gio;
use crate::http::http_request::{HttpMethod, HttpRequest, HttpVersion};
use crate::http::http_response::HttpResponse;
use crate::http_client::http_client::HttpClient;
use crate::util::cookie_parse::cookie_parse;

const GITEE_OAUTH_URL: &str = "https://gitee.com/oauth/token";

const GITEE_USER_INFO_URL: &str = "https://gitee.com/api/v5/user";

const GITEE_OAUTH_CLIENT_ID: &str = "b9791c72cab5064926ced23043e0753e273315e47d1644c04a09a1aca8db7c51";

const GITEE_OAUTH_CLIENT_SECRET: &str = "a4970695ad5c6274122d0cb8f312490ce5eadab080735f7810b79bfc6bdcd368";

const GITEE_OAUTH_REDIRECT_URI: &str = "http://wujianming.xyz";
pub async fn oauth2_handler(request: &HttpRequest, response: &mut HttpResponse) -> Result<(), Box<dyn std::error::Error>> {

    debug!("oauth2_handler Request: {:?}", request);

    let code = request.params.get("code").unwrap();

    let body_str = format!("grant_type=authorization_code&code={code}&client_id={GITEE_OAUTH_CLIENT_ID}&client_secret={GITEE_OAUTH_CLIENT_SECRET}&redirect_uri={GITEE_OAUTH_REDIRECT_URI}");


    let response_post = HttpClient::send_post(GITEE_OAUTH_URL.parse().unwrap(), body_str).await.unwrap();

    let token_response: Value = serde_json::from_str(response_post.as_str())?;

    debug!("oauth2_handler Response: {:?}", token_response);

    // if token_response["access_token"] && token_response["refresh_token"] {
    //     // 存储 token 到数据库
    //     // ...
    //
    //     let response_get = HttpClient::send_get(GITEE_USER_INFO_URL.parse().unwrap(), &token_response["access_token"]);
    //
    //     let user_info = serde_json::from_str(response_get.as_str())?;
    //
    //     debug!("oauth2_handler Response_get: id: {:?} login: {:?} avatar_url: {:?}", user_info["id"], user_info["login"], user_info["avatar_url"]);
    //
    //     let mut gio = get_gio().write().unwrap();
    //
    //     let cookie = cookie_parse(request);
    //
    //     let session_id = cookie.get("session_id").unwrap();
    //
    //     let user_str = gio.get(session_id).unwrap();
    //
    //     let mut user: HashMap<String, String> = serde_json::from_str(user_str).unwrap();
    //
    //     user.insert("access_token".to_string(), token_response["access_token"].to_string());
    //
    //     user.insert("refresh_token".to_string(), token_response["refresh_token"].to_string());
    //
    //     user.insert("id".to_string(), user_info["id"].to_string());
    //
    //     user.insert("name".to_string(), user_info["login"].to_string());
    //
    //     user.insert("avatar_url".to_string(), user_info["avatar_url"].to_string());
    //
    //     gio.insert(session_id.to_string(), serde_json::to_string(&user).unwrap());
    //
    // } else {
    //
    // }

    // 检查 access_token 和 refresh_token 是否存在且为字符串
    if let Some(access_token) = token_response["access_token"].as_str() {
        if let Some(refresh_token) = token_response["refresh_token"].as_str() {
            // 存储 token 到数据库
            // ...

            let response_get = HttpClient::send_get(
                GITEE_USER_INFO_URL.parse().unwrap(),
                access_token,
            ).await.unwrap();

            let user_info: Value = serde_json::from_str(response_get.as_str())?;

            debug!(
                "oauth2_handler Response_get: id: {:?} name: {:?} avatar_url: {:?}",
                user_info["id"], user_info["name"], user_info["avatar_url"]
            );

            let mut gio = get_gio().write().expect("拿不到锁");

            let cookie = cookie_parse(request);

            let session_id = cookie.get("session_id").unwrap();

            let user_str = gio.get(session_id).unwrap();

            let mut user: Value = serde_json::from_str(user_str)?;

            debug!("oauth2_handler user before: {:?}", user);

            if let Some(user_obj) = user.as_object_mut() {

                user_obj.insert("id".to_string(), user_info["id"].clone());
                user_obj.insert("name".to_string(), user_info["name"].clone());
                user_obj.insert("avatar_url".to_string(), user_info["avatar_url"].clone());
                user_obj.insert("access_token".to_string(), Value::from(access_token.to_string()));
                user_obj.insert("refresh_token".to_string(), Value::from(refresh_token.to_string()));

            }

            debug!("oauth2_handler user after: {:?}", user);

            gio.insert(session_id.to_string(), serde_json::to_string(&user)?);
        } else {
            return Err("Missing refresh_token in token_response".into());
        }
    } else {
        return Err("Missing access_token in token_response".into());
    }

    HttpResponse::ok_no_body(response);

    Ok(())
}
